package com.afly.netty.business.controller;

import com.afly.netty.business.domain.EasyResult;
import com.afly.netty.util.CacheUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@Slf4j
public class CommandController {
    //向指定设备下达指令
    @PostMapping("/doSendCommand")
    public EasyResult doSendCommand(String deviceNum, String command) {
        try {
            String channelId = null;
            Map<String, String> deviceChannelMap = CacheUtil.deviceChannelMap;
            for (Map.Entry<String, String> entry : deviceChannelMap.entrySet()) {
                if (entry.getValue().equals(deviceNum)) {
                    channelId = entry.getKey();
                }
            }
            if (channelId == null) return EasyResult.buildErrResult("设备链接不存在，可能下线");

            log.info("向设备{}发送command===>{}",deviceNum,command);
            Channel channel = CacheUtil.cacheClientChannel.get(channelId);

            channel.writeAndFlush(command);
            return EasyResult.buildSuccessResult();
        } catch (Exception e) {
            log.error("向设备发{}送信息{}失败：{}", deviceNum, command, e);
            return EasyResult.buildErrResult(e);
        }
    }
}
